my $pvalue=$ARGV[0];
my $num=$ARGV[1];
my $dir=$ARGV[2];
opendir(DH,"$dir") or die;
my @out_normal;
my @out_tumor;
foreach my $file(readdir(DH)){
	if($file=~/methylCGsRich_ASM_AllSnp_(\w+)Merge_(\w+)_pValue.txt/){
		my $sample=$1;
		my $chr=$2;
		next if $chr eq "chrX";
		next if $chr eq "chrY";
		next if $chr eq "chrM";
		$file=$dir.$file;
		open(FH,"<$file") or die;
		my @in=<FH>;
		chomp(@in);
		close(FH);
		if($sample eq "normal"){
			my $count = 1;
			foreach my $line(@in){
				my @splitin = split "\t",$line;

				if($splitin[2] < $pvalue){
					push(@out_normal,"$chr\t$line\n");
					foreach my $myline(@in){
						my @splitmyline = split "\t",$myline;
						if($splitmyline[2] < $pvalue && $splitmyline[0] == $splitin[0] && $splitmyline[1] != $splitin[1]){
							$count++;
						}
					}
					if($count < $num){
						pop(@out_normal);
					}
					$count = 1;
				}
			}
		}
		else{
			my $count = 1;
			foreach my $line(@in){
				my @splitin = split "\t",$line;

				if($splitin[2] < $pvalue){
					push(@out_tumor,"$chr\t$line\n");
					foreach my $myline(@in){
						my @splitmyline = split "\t",$myline;
						if($splitmyline[2] < $pvalue && $splitmyline[0] == $splitin[0] && $splitmyline[1] != $splitin[1]){
							$count++;
						}
					}
					if($count < $num){
						pop(@out_tumor);
					}
					$count = 1;
				}
			}
		}
		
		
	}
}
my $out_normal_file=$dir."methylCGsRich_ASM_AllSnp_normalMerge_sigGroup-".$num.".".$pvalue.".txt";
open(OUT,">$out_normal_file");
print OUT @out_normal;
close(OUT);
my $out_tumor_file=$dir."methylCGsRich_ASM_AllSnp_tumorMerge_sigGroup-".$num.".".$pvalue.".txt";
open(OUT,">$out_tumor_file");
print OUT @out_tumor;
close(OUT);
